package com.jkgj.skykingkong.tms.infrastructure.security;

import com.jkgj.skykingkong.tms.domain.model.rbac.Role;
import com.jkgj.skykingkong.tms.domain.model.rbac.User;
import com.jkgj.skykingkong.tms.domain.model.rbac.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Xuegui Yuan
 */
@Component
public class UserDetailsQueryService implements UserDetailsService {
  @Autowired
  private UserRepository userRepository;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userRepository.findUserByUsername(username);
    if (user == null) {
      throw new UsernameNotFoundException("用户不存在");
    }
    // 定义权限集合
    List<SimpleGrantedAuthority> grantedAuthorities = new ArrayList<SimpleGrantedAuthority>();
    List<Role> roles = user.getRoles();
    // 添加权限到集合中
    for (Role role : roles) {
      grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + role.getCode()));
    }
    return new org.springframework.security.core.userdetails.User(user.getUsername(),
        user.getPassword(),
        user.isEnabled(),
        true,
        true,
        true,
        grantedAuthorities);
  }
}
